<!--TtsImportTranslation.vue-->
<template>
  <t-dialog
    v-model:visible="dialogVisible"
    header="文本导入与处理"
    :footer="false"
    width="900px"
    destroyOnClose
    class="tts-import-translation-dialog"
  >
    <div class="tts-import-translation">
      <!-- 步骤导航 -->
      <div class="steps-container">
        <t-steps :current="currentStepIndex" class="process-steps">
          <t-step-item title="导入文本" content="从文本框或Excel导入文本内容" />
          <t-step-item title="翻译处理" content="可选步骤，可进行文本翻译" />
          <t-step-item title="导入TTS" content="导入到TTS处理进行语音合成" />
        </t-steps>
      </div>

      <!-- 导入区域 -->
      <div class="import-section" v-if="step === 'import'">
        <div class="import-options">
          <t-tabs v-model="importTab">
            <t-tab-panel value="text" label="直接输入">
              <div class="text-import">
                <!-- 添加模型提示信息 -->
                <div class="model-info-wrapper" v-if="modelType">
                  <t-alert :theme="getAlertTheme()" class="model-info-alert">
                    <template #title>
                      <span>{{ getModelTitle() }}</span>
                    </template>
                    <div>
                      <p>{{ getModelDescription() }}</p>
                    </div>
                  </t-alert>
                </div>

                <t-textarea
                  v-model="importState.textContent"
                  :placeholder="importState.textPlaceholder"
                  :autosize="{ minRows: 10, maxRows: 20 }"
                />
              </div>
            </t-tab-panel>

            <t-tab-panel value="excel" label="Excel导入">
              <div class="excel-import">
                <div v-if="!importState.excelData" class="file-upload-area">
                  <div class="excel-file-selector">
                    <t-button @click="selectExcelFile">选择Excel文件</t-button>
                    <p class="tip">支持 .xlsx, .xls 格式</p>
                  </div>
                </div>

                <div v-else class="excel-preview">
                  <div class="column-selection">
                    <div class="selection-row">
                      <div class="selection-label">标题列:</div>
                      <t-select v-model="importState.titleColumnIndex" placeholder="选择标题列">
                        <t-option
                          v-for="(column, index) in importState.headers"
                          :key="index"
                          :value="index"
                          :label="column || `列 ${index + 1}`"
                        />
                      </t-select>
                    </div>
                    <div class="selection-row">
                      <div class="selection-label">内容列:</div>
                      <t-select v-model="importState.contentColumnIndex" placeholder="选择内容列">
                        <t-option
                          v-for="(column, index) in importState.headers"
                          :key="index"
                          :value="index"
                          :label="column || `列 ${index + 1}`"
                        />
                      </t-select>
                    </div>
                  </div>

                  <div class="preview-table">
                    <t-table
                      :data="importState.previewData"
                      row-key="index"
                      :max-height="300"
                      bordered
                      stripe
                    >
                      <t-thead>
                        <t-tr>
                          <t-th v-for="(header, index) in importState.headers" :key="index">
                            {{ header || `列 ${index + 1}` }}
                          </t-th>
                        </t-tr>
                      </t-thead>
                      <t-tbody>
                        <t-tr v-for="(row, rowIndex) in importState.previewData" :key="rowIndex">
                          <t-td v-for="(_, colIndex) in importState.headers" :key="colIndex">
                            {{ row[colIndex] }}
                          </t-td>
                        </t-tr>
                      </t-tbody>
                    </t-table>
                  </div>
                </div>
              </div>
            </t-tab-panel>
          </t-tabs>
        </div>

        <div class="section-footer">
          <t-space>
            <t-button theme="default" @click="cancel">取消</t-button>
            <t-button theme="primary" :loading="importState.importing" @click="handleImport">导入</t-button>
          </t-space>
        </div>
      </div>

      <!-- 翻译区域 -->
      <div class="translation-section" v-if="step === 'translate'">
        <div class="section-header">
          <div class="section-title">翻译文本</div>
        </div>

        <!-- 翻译设置 -->
        <div class="translation-area">
          <div class="translation-header">
            <div class="translation-title">翻译设置</div>
          </div>

          <!-- 翻译选项 -->
          <div class="translation-options">
            <div class="setting-item">
              <div class="setting-label">目标语言:</div>
              <t-select
                v-model="selectedLanguage"
                placeholder="选择翻译目标语言"
                class="setting-select"
              >
                <t-option
                  v-for="language in targetLanguages"
                  :key="language.code"
                  :value="language.name"
                  :label="language.name"
                >

                </t-option>
              </t-select>
              <t-button
                theme="primary"
                :loading="isTranslating"
                :disabled="isTranslating || selectedItems.length === 0"
                @click="translateSelected"
              >
                {{ isTranslating ? '翻译中...' : '翻译选中' }}
              </t-button>

              <t-button
                theme="success"
                :loading="isTranslating"
                :disabled="isTranslating || textItems.length === 0"
                @click="translateAll"
              >
                {{ isTranslating ? '翻译中...' : '翻译全部' }}
              </t-button>
            </div>
          </div>

          <!-- 翻译进度展示 -->
          <div class="translation-progress" v-if="isTranslating">
            <t-progress :percentage="progressPercentage" :label="progressLabel" status="active" />
          </div>
        </div>

        <!-- 多选操作栏 -->
        <div class="batch-actions" v-if="textItems.length > 0">
          <t-checkbox
            v-model="selectMode"
            @change="toggleSelectMode"
          >
            <span>多选模式</span>
          </t-checkbox>

          <template v-if="selectMode">
            <div class="batch-info">已选择 {{ selectedItems.length }} 项</div>
            <div class="batch-controls">
              <t-button
                size="small"
                @click="selectCurrentPage"
                v-if="getCurrentPageItems().length > 0 && !isCurrentPageFullySelected"
              >
                选择当前页
              </t-button>
              <t-button
                size="small"
                @click="deselectCurrentPage"
                v-if="getCurrentPageItems().length > 0 && hasCurrentPageSelected"
              >
                取消选择当前页
              </t-button>
              <t-button
                size="small"
                @click="deselectAllItems"
                v-if="selectedItems.length > 0"
              >
                清除选择
              </t-button>
              <t-button
                size="small"
                theme="danger"
                @click="batchDelete"
                v-if="selectedItems.length > 0"
              >
                批量删除
              </t-button>
            </div>
          </template>
        </div>

        <!-- 文本列表 -->
        <div class="text-list-container">
          <div class="text-list-header">
            <div class="list-title">已导入文本 ({{ textItems.length }})</div>
            <div class="list-actions">
              <t-button variant="text" theme="danger" size="small" @click="clearAll">
                清空
              </t-button>
            </div>
          </div>

          <div class="text-items">
            <div
              v-for="item in getCurrentPageItems()"
              :key="item.id"
              class="text-item"
              :class="{
                translated: item.translated,
                selected: selectedItems.includes(item.id)
              }"
              @click="selectMode ? toggleSelectItem(item.id) : null"
            >
              <!-- 选择框 -->
              <div class="item-select" v-if="selectMode">
                <t-checkbox
                  :checked="selectedItems.includes(item.id)"
                  @change="toggleSelectItem(item.id)"
                  @click.stop
                />
              </div>

              <!-- 文本内容 -->
              <div class="text-content">
                <div class="text-title">
                  {{ item.name || '未命名' }}
                  <t-tag v-if="item.translated" size="small" theme="success" class="translated-tag">已翻译</t-tag>
                </div>
                <div class="text-preview">
                  {{ item.text.substring(0, 50) + (item.text.length > 50 ? '...' : '') }}
                </div>
              </div>
              <t-button theme="warning" @click.stop="showItemDetail(item)" size="small">查看详情</t-button>
            </div>
          </div>

          <!-- 分页控件 -->
          <div
            class="pagination-container"
            v-if="textItems.length > pagination.pageSize"
          >
            <t-pagination
              v-model="pagination.current"
              v-model:pageSize="pagination.pageSize"
              :total="textItems.length"
              :page-size-options="[5, 10, 15, 50, 100]"
              @change="onPageChange"
              @page-size-change="onPageSizeChange"
            />
          </div>
        </div>

        <div class="section-footer">
          <t-space>
            <t-button theme="default" @click="goBack">上一步</t-button>
            <t-button theme="primary" @click="importToParent">跳过翻译并导入</t-button>
            <t-button theme="success" @click="importToParent">完成翻译并导入</t-button>
          </t-space>
        </div>
      </div>

      <!-- 导入确认区域 -->
      <div class="confirm-section" v-if="step === 'confirm'">
        <div class="section-header">
          <div class="section-title">导入确认</div>
        </div>

        <div class="confirm-content">
          <t-alert theme="success" class="confirm-alert">
            <template #title>
              <span>即将导入到TTS处理</span>
            </template>
            <div>
              <p>您即将导入 {{ textItems.length }} 篇文本到TTS处理系统进行语音合成。</p>
              <p>已翻译文本数量：{{ translatedCount }}</p>
              <p>未翻译文本数量：{{ untranslatedCount }}</p>
            </div>
          </t-alert>

          <div class="confirm-summary">
            <t-table
              :data="summaryData"
              :columns="summaryColumns"
              row-key="id"
              :max-height="300"
              stripe
              bordered
            />
          </div>
        </div>

        <div class="section-footer">
          <t-space>
            <t-button theme="default" @click="goBack">上一步</t-button>
            <t-button theme="primary" @click="finalImport">确认导入</t-button>
          </t-space>
        </div>
      </div>
    </div>

    <!-- 确认对话框 -->
    <t-dialog
      v-model:visible="confirmDialogVisible"
      header="确认操作"
      :confirm-btn="{ content: '确认', theme: 'danger' }"
      :cancel-btn="{ content: '取消' }"
      @confirm="confirmAction"
    >
      <p>{{ confirmMessage }}</p>
    </t-dialog>

    <!-- 详情查看对话框 -->
    <t-dialog
      v-model:visible="detailDialogVisible"
      header="文本详情"
      :footer="false"
      width="700px"
      class="text-detail-dialog"
    >
      <div class="detail-content" v-if="currentDetailItem">
        <div class="detail-section">
          <div class="detail-title">标题</div>
          <div class="detail-value">
            <div class="original-text" v-if="currentDetailItem.originalName && currentDetailItem.translated">
              <div class="text-label">原文:</div>
              <div class="text-content">{{ currentDetailItem.originalName }}</div>
            </div>
            <div class="translated-text" :class="{ 'has-original': currentDetailItem.originalName && currentDetailItem.translated }">
              <div class="text-label" v-if="currentDetailItem.translated">翻译:</div>
              <div class="text-content">{{ currentDetailItem.name || '未命名' }}</div>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <div class="detail-title">内容</div>
          <div class="detail-value">
            <div class="original-text" v-if="currentDetailItem.originalText && currentDetailItem.translated">
              <div class="text-label">原文:</div>
              <div class="text-content scrollable">{{ currentDetailItem.originalText }}</div>
            </div>
            <div class="translated-text" :class="{ 'has-original': currentDetailItem.originalText && currentDetailItem.translated }">
              <div class="text-label" v-if="currentDetailItem.translated">翻译:</div>
              <div class="text-content scrollable">{{ currentDetailItem.text }}</div>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <div class="detail-title">状态信息</div>
          <div class="detail-value">
            <div class="status-info">
              <t-tag :theme="currentDetailItem.translated ? 'success' : 'default'">
                {{ currentDetailItem.translated ? '已翻译' : '未翻译' }}
              </t-tag>
              <span class="create-time">创建时间: {{ formatTime(currentDetailItem.createdAt) }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="detail-footer">
        <t-space>
          <t-button theme="default" @click="detailDialogVisible = false">关闭</t-button>
          <t-button
            theme="primary"
            v-if="!currentDetailItem?.translated && selectedLanguage"
            :loading="isTranslatingDetail"
            @click="translateDetailItem"
          >
            {{ isTranslatingDetail ? '翻译中...' : '翻译此项' }}
          </t-button>
        </t-space>
      </div>
    </t-dialog>
  </t-dialog>
</template>

<script setup>
import { ref, computed, reactive, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { v4 as uuidv4 } from 'uuid';
import * as XLSX from 'xlsx';
import { translateText } from '@renderer/api/translateApi';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  modelType: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['update:visible', 'import-items', 'cancel']);

// 步骤状态
const step = ref('import'); // 'import', 'translate', 'confirm'

// 计算当前步骤索引
const currentStepIndex = computed(() => {
  switch (step.value) {
    case 'import':
      return 0;
    case 'translate':
      return 1;
    case 'confirm':
      return 2;
    default:
      return 0;
  }
});

const dialogVisible = ref(false)

// 导入选项卡状态
const importTab = ref('text');

// 导入状态对象
const importState = reactive({
  // 文本导入相关
  textContent: '',
  textPlaceholder: '请输入要导入的文本内容，导入多篇，请使用 "---文章1---" 分割',

  // Excel导入相关
  file: null,
  excelData: null,
  headers: [],
  previewData: [],
  titleColumnIndex: null,
  contentColumnIndex: null,

  // 通用状态
  importing: false,
});

// 文本列表状态
const textItems = ref([]);
const selectMode = ref(false);
const selectedItems = ref([]);

// 分页状态
const pagination = reactive({
  current: 1,
  pageSize: 10
});

// 翻译状态
const selectedLanguage = ref(null);
const isTranslating = ref(false);
const currentIndex = ref(0);
const totalItemsToTranslate = ref(0);

// 确认对话框
const confirmDialogVisible = ref(false);
const confirmMessage = ref('');
const confirmCallback = ref(null);

// 详情对话框相关状态
const detailDialogVisible = ref(false);
const currentDetailItem = ref(null);
const isTranslatingDetail = ref(false);

// 显示项目详情
const showItemDetail = (item) => {
  console.log(currentDetailItem.value);
  currentDetailItem.value = item;
  detailDialogVisible.value = true;
};

// 格式化时间函数
const formatTime = (timeString) => {
  if (!timeString) return '未知';

  try {
    const date = new Date(timeString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (error) {
    return '未知';
  }
};

// 翻译详情中的单个项目
const translateDetailItem = async () => {
  if (!currentDetailItem.value || !selectedLanguage.value) {
    MessagePlugin.warning('请先选择目标语言');
    return;
  }

  isTranslatingDetail.value = true;

  try {
    // 翻译标题和内容
    const [translatedName, translatedText] = await Promise.all([
      currentDetailItem.value.name ? translateText(currentDetailItem.value.name, 'auto', selectedLanguage.value) : Promise.resolve(currentDetailItem.value.name),
      translateText(currentDetailItem.value.text, 'auto', selectedLanguage.value)
    ]);

    // 更新当前详情项
    currentDetailItem.value.name = translatedName || currentDetailItem.value.name;
    currentDetailItem.value.text = translatedText;
    currentDetailItem.value.translated = true;

    // 同时更新主列表中的对应项
    const itemIndex = textItems.value.findIndex(item => item.id === currentDetailItem.value.id);
    if (itemIndex !== -1) {
      textItems.value[itemIndex] = { ...currentDetailItem.value };
    }

    MessagePlugin.success('翻译完成');

    console.log(currentDetailItem.value);
  } catch (error) {
    console.error('翻译失败:', error);
    MessagePlugin.error(`翻译失败: ${error.message || '未知错误'}`);
  } finally {
    isTranslatingDetail.value = false;
  }
};

// 确认页面表格列定义
const summaryColumns = [
  { colKey: 'name', title: '标题', width: '30%' },
  { colKey: 'text', title: '内容预览', width: '50%' },
  { colKey: 'status', title: '状态', width: '20%' },
];

// 确认页面表格数据
const summaryData = computed(() => {
  return textItems.value.map(item => ({
    id: item.id,
    name: item.name,
    text: item.text.substring(0, 30) + (item.text.length > 30 ? '...' : ''),
    status: item.translated ? '已翻译' : '未翻译'
  }));
});

// 计算已翻译和未翻译的数量
const translatedCount = computed(() => {
  return textItems.value.filter(item => item.translated).length;
});

const untranslatedCount = computed(() => {
  return textItems.value.length - translatedCount.value;
});

// 可选的目标语言
const targetLanguages = [
  { code: 'zh-CN', name: '中文（简体）' },
  { code: 'en', name: '英语' },
  { code: 'th', name: '泰语' },
  { code: 'vi', name: '越南语' },
];

// 判断模型类型的计算属性
const isTtsModel = computed(() => {
  return props.modelType === 'tts-1' || props.modelType === 'tts-1-hd';
});

const isGpt4oModel = computed(() => {
  return props.modelType === 'gpt-4o-audio-preview' || props.modelType === 'gpt-4o-mini-audio-preview';
});

const isCustomVoiceModel = computed(() => {
  return props.modelType === 'gpt-4o-mini-tts';
});

// 获取当前页文本项
const getCurrentPageItems = () => {
  const startIndex = (pagination.current - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  return textItems.value.slice(startIndex, endIndex);
};

// 计算当前页是否全部选中
const isCurrentPageFullySelected = computed(() => {
  const currentPageItems = getCurrentPageItems();
  return currentPageItems.length > 0 &&
    currentPageItems.every(item => selectedItems.value.includes(item.id));
});

// 计算当前页是否有选中项
const hasCurrentPageSelected = computed(() => {
  const currentPageItems = getCurrentPageItems();
  return currentPageItems.some(item => selectedItems.value.includes(item.id));
});

// 获取提示信息标题
const getModelTitle = () => {
  if (isTtsModel.value) {
    return '标准TTS模型导入提示';
  } else if (isGpt4oModel.value) {
    return '多语言模型导入提示';
  } else if (isCustomVoiceModel.value) {
    return '自定义语音模型导入提示';
  }
  return '文本导入提示';
};

// 获取提示信息描述
const getModelDescription = () => {
  if (isTtsModel.value) {
    return '请确保您导入的文本已经是目标语言。此模型不会自动翻译内容，仅朗读您提供的文本。';
  } else if (isGpt4oModel.value) {
    return '您可以导入任何语言的原始文本，选择目标语言后，系统将自动翻译并生成语音。';
  } else if (isCustomVoiceModel.value) {
    return '请确保您导入的文本已是目标语言，您可以在后续步骤添加语音指令来自定义语音特性。';
  }
  return '请导入需要合成语音的文本内容。';
};

// 获取提示框主题颜色
const getAlertTheme = () => {
  if (isTtsModel.value) {
    return 'info';
  } else if (isGpt4oModel.value) {
    return 'warning';
  } else if (isCustomVoiceModel.value) {
    return 'success';
  }
  return 'info';
};

// 计算属性：翻译进度百分比
const progressPercentage = computed(() => {
  if (totalItemsToTranslate.value === 0) return 0;
  return Math.round((currentIndex.value / totalItemsToTranslate.value) * 100);
});

// 计算属性：翻译进度标签
const progressLabel = computed(() => {
  return `${currentIndex.value}/${totalItemsToTranslate.value}`;
});

// 监听visible变化，重置状态
watch(() => props.visible, (newVisible) => {
  dialogVisible.value = newVisible
  if (newVisible) {
    // 对话框打开时，设置为导入步骤
    step.value = 'import';
  } else {
    resetState();
  }
});

// 监听内部 dialogVisible 的变化，同步到父组件
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    step.value = 'import';
    emit('update:visible', false)
  }
})

// 重置状态
const resetState = () => {
  step.value = 'import';
  importTab.value = 'text';
  importState.textContent = '';
  importState.file = null;
  importState.excelData = null;
  importState.headers = [];
  importState.previewData = [];
  importState.titleColumnIndex = null;
  importState.contentColumnIndex = null;
  importState.importing = false;
  textItems.value = [];
  selectMode.value = false;
  selectedItems.value = [];
  isTranslating.value = false;
  currentIndex.value = 0;
  totalItemsToTranslate.value = 0;
  pagination.current = 1;
  pagination.pageSize = 10;
};

// 回到上一步
const goBack = () => {
  if (step.value === 'translate') {
    step.value = 'import';
  } else if (step.value === 'confirm') {
    step.value = 'translate';
  }
};

// 分页方法
const onPageChange = (pageInfo) => {
  pagination.current = pageInfo.current;
};

const onPageSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  pagination.current = 1; // 重置到第一页
};

// 多选模式切换
const toggleSelectMode = (checked) => {
  selectMode.value = checked;
  if (!checked) {
    // 关闭多选模式时清空选择
    selectedItems.value = [];
  }
};

// 选择当前页所有项目
const selectCurrentPage = () => {
  const currentPageItems = getCurrentPageItems();
  const currentPageIds = currentPageItems.map(item => item.id);

  // 合并当前已选择的和当前页的ID，避免重复
  selectedItems.value = [...new Set([...selectedItems.value, ...currentPageIds])];

  MessagePlugin.success(`已选择当前页 ${currentPageItems.length} 项`);
};

// 取消选择当前页所有项目
const deselectCurrentPage = () => {
  const currentPageIds = getCurrentPageItems().map(item => item.id);
  selectedItems.value = selectedItems.value.filter(id => !currentPageIds.includes(id));

  MessagePlugin.success(`已取消选择当前页`);
};

// 取消选择所有项目
const deselectAllItems = () => {
  selectedItems.value = [];
  MessagePlugin.success('已清除所有选择');
};

// 批量删除选中项目
const batchDelete = () => {
  if (selectedItems.value.length === 0) {
    MessagePlugin.warning('请先选择需要删除的项目');
    return;
  }

  confirmMessage.value = `确定要删除选中的 ${selectedItems.value.length} 项吗？此操作不可恢复。`;
  confirmCallback.value = () => {
    textItems.value = textItems.value.filter(item => !selectedItems.value.includes(item.id));
    selectedItems.value = [];
    MessagePlugin.success('批量删除成功');

    // 如果当前页没有数据了，且不是第一页，则回到上一页
    if (getCurrentPageItems().length === 0 && pagination.current > 1) {
      pagination.current -= 1;
    }
  };
  confirmDialogVisible.value = true;
};

// 选择Excel文件
const selectExcelFile = async () => {
  try {
    // 模拟文件选择对话框
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx,.xls';

    input.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      // 显示加载提示
      MessagePlugin.loading('正在读取Excel文件...');

      try {
        // 读取Excel文件
        const reader = new FileReader();
        reader.onload = (event) => {
          try {
            const data = new Uint8Array(event.target.result);
            const workbook = XLSX.read(data, { type: 'array' });

            // 获取第一个工作表
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];

            // 转换为JSON
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

            if (jsonData.length === 0) {
              MessagePlugin.warning('Excel文件为空');
              return;
            }

            // 提取表头和数据
            const headers = jsonData[0];
            const previewData = jsonData.slice(1, Math.min(6, jsonData.length)); // 取前5行作为预览

            // 更新状态
            importState.excelData = jsonData;
            importState.headers = headers;
            importState.previewData = previewData;

            // 自动检测标题和内容列
            findTitleContentColumns(headers);

            MessagePlugin.success('Excel文件读取成功');
          } catch (error) {
            console.error('解析Excel文件失败:', error);
            MessagePlugin.error('解析Excel文件失败: ' + (error.message || '未知错误'));
          }
        };

        reader.onerror = () => {
          MessagePlugin.error('读取文件失败');
        };

        reader.readAsArrayBuffer(file);
      } catch (error) {
        console.error('读取Excel文件失败:', error);
        MessagePlugin.error('读取Excel文件失败: ' + (error.message || '未知错误'));
      }
    };

    input.click();
  } catch (error) {
    console.error('选择Excel文件失败:', error);
    MessagePlugin.error('选择Excel文件失败: ' + (error.message || '未知错误'));
  }
};

const findTitleContentColumns = (headers) => {
  // 如果未传入 headers 或数组为空，则直接返回
  if (!headers || headers.length === 0) return;

  // 定义匹配标题和内容的关键词列表
  const titleKeywords = ['标题', 'title', '名称', 'name', '主题', 'subject'];
  const contentKeywords = ['内容', 'content', '正文', 'body', '描述', 'description', 'text'];

  // 初始化变量，用于记录匹配到的标题和内容列索引，默认值为 -1 表示未匹配到
  let titleIndex = -1;
  let contentIndex = -1;

  // 遍历 headers，依次检查每个表头是否包含任一关键词
  headers.forEach((header, index) => {
    if (typeof header !== 'string') return;

    // 标题列：优先匹配 titleKeywords 中的任一关键词
    if (titleIndex === -1 && titleKeywords.some(keyword => header.toLowerCase().includes(keyword.toLowerCase()))) {
      titleIndex = index;
    }
    // 内容列：优先匹配 contentKeywords 中的任一关键词
    if (contentIndex === -1 && contentKeywords.some(keyword => header.toLowerCase().includes(keyword.toLowerCase()))) {
      contentIndex = index;
    }
  });

  // 当没有通过关键词匹配到有效列时，采用默认策略：
  // 将第一列作为标题列，第二列作为内容列（如果存在）
  if (titleIndex === -1 && headers.length > 0) {
    titleIndex = 0;
  }
  if (contentIndex === -1 && headers.length > 1) {
    contentIndex = 1;
  }

  // 更新状态
  importState.titleColumnIndex = titleIndex;
  importState.contentColumnIndex = contentIndex;

  // 通过消息插件向用户提示推荐选项
  if (headers.length > 1) {
    MessagePlugin.info(`已自动选择标题列和内容列，您可以手动调整`);
  }
};

// 处理导入操作
const handleImport = async () => {
  importState.importing = true;

  try {
    let items = [];

    if (importTab.value === 'text') {
      items = await handleTextImport();
    } else if (importTab.value === 'excel') {
      items = await handleExcelImport();
    }

    if (items && items.length > 0) {
      textItems.value = items;
      step.value = 'translate';
      pagination.current = 1; // 导入后重置到第一页
      MessagePlugin.success(`成功导入 ${items.length} 篇文章`);
    }
  } catch (error) {
    console.error('导入失败:', error);
    MessagePlugin.error('导入失败: ' + (error.message || '未知错误'));
  } finally {
    importState.importing = false;
  }
};

// 文本导入处理
const handleTextImport = async () => {
  const text = importState.textContent.trim();

  if (!text) {
    MessagePlugin.warning('请输入有效的文本内容');
    return [];
  }

  const textParts = parseTextContent(text);

  console.log(textParts);

  if (textParts.length === 0) {
    MessagePlugin.warning('未找到有效的文本内容');
    return [];
  }

  return textParts.map(part => ({
    id: uuidv4(),
    type: 'text',
    name: part.title,
    text: part.content,
    originalText: part.content,
    originalName: part.title,
    translated: false,
    createdAt: new Date().toISOString(),
  }));
};

// Excel导入处理
const handleExcelImport = async () => {
  if (!importState.excelData) {
    MessagePlugin.warning('请先上传Excel文件');
    return [];
  }

  if (importState.titleColumnIndex === null || importState.contentColumnIndex === null) {
    MessagePlugin.warning('请选择标题列和内容列');
    return [];
  }

  // 跳过表头行，处理所有数据行
  const dataRows = importState.excelData.slice(1);
  const textItems = [];

  for (const row of dataRows) {
    // 检查数据行是否有效
    if (!row || row.length === 0) continue;

    const title = row[importState.titleColumnIndex] || '未命名';
    const content = row[importState.contentColumnIndex];

    // 只有内容不为空的才添加
    if (content) {
      textItems.push({
        id: uuidv4(),
        type: 'text',
        name: String(title),
        text: String(content),
        originalText: String(title),
        originalName: String(content),
        translated: false,
        createdAt: new Date().toISOString(),
      });
    }
  }

  if (textItems.length === 0) {
    MessagePlugin.warning('未找到有效的内容');
    return [];
  }

  return textItems;
};

// 解析文本内容，处理 ---xxx--- 格式
const parseTextContent = (text) => {
  // 检查是否包含 ---xxx--- 格式的分隔符
  if (text.match(/^---.*---$/m)) {
    // 使用正则表达式分割文本
    const pattern = /(^|\n)---(.*?)---\s*\n/g;
    const parts = text.split(pattern).filter(part => part.trim() && !part.match(/^---.*---$/));

    // 将分割后的文本和标题组合起来
    const result = [];
    for (let i = 0; i < parts.length; i += 2) {
      const title = parts[i].trim();
      const content = (i + 1 < parts.length) ? parts[i + 1].trim() : '';

      if (content) {
        result.push({
          title: title,
          content: content
        });
      }
    }

    return result;
  } else {
    // 如果没有找到分隔符，则按行分割
    return text.split('\n')
      .map(line => line.trim())
      .filter(line => line.length > 0)
      .map(line => ({
        title: line.substring(0, 20) + (line.length > 20 ? '...' : ''),
        content: line
      }));
  }
};

// 切换选择项目
const toggleSelectItem = (id) => {
  if (selectedItems.value.includes(id)) {
    selectedItems.value = selectedItems.value.filter(itemId => itemId !== id);
  } else {
    selectedItems.value.push(id);
  }
};

// 清空所有文本
const clearAll = () => {
  if (textItems.value.length === 0) return;

  confirmMessage.value = '确定要清空所有文本吗？此操作不可恢复。';
  confirmCallback.value = () => {
    textItems.value = [];
    selectedItems.value = [];
    pagination.current = 1;
    MessagePlugin.success('已清空所有文本');
  };
  confirmDialogVisible.value = true;
};

// 确认操作
const confirmAction = () => {
  if (typeof confirmCallback.value === 'function') {
    confirmCallback.value();
  } else {
    // 用户取消了翻译操作，直接进入确认步骤
    if (confirmMessage.value.includes('是否需要进行翻译处理')) {
      step.value = 'confirm';
    }
  }
  confirmDialogVisible.value = false;
};

// 翻译选中项目
const translateSelected = async () => {
  if (selectedItems.value.length === 0) {
    MessagePlugin.warning('请先选择需要翻译的文本');
    return;
  }

  // 获取选中的项目
  const itemsToTranslate = textItems.value.filter(item => selectedItems.value.includes(item.id));
  await startTranslation(itemsToTranslate);
};

// 翻译所有项目
const translateAll = async () => {
  if (textItems.value.length === 0) {
    MessagePlugin.warning('没有可翻译的文本');
    return;
  }

  await startTranslation([...textItems.value]);
};

// 启动翻译过程
const startTranslation = async (items) => {
  if (isTranslating.value) return;

  try {
    isTranslating.value = true;
    currentIndex.value = 0;
    totalItemsToTranslate.value = items.length;

    // 创建一个新的数组来保存所有项目
    const updatedItems = [...textItems.value];

    // 逐个翻译项目
    for (const item of items) {
      // 更新计数器
      currentIndex.value++;

      try {
        // 翻译标题和内容
        const [translatedName, translatedText] = await Promise.all([
          item.name ? translateText(item.name, 'auto', selectedLanguage.value) : Promise.resolve(item.name),
          translateText(item.text, 'auto', selectedLanguage.value)
        ]);

        // 在原始数组中找到并更新该项目
        const itemIndex = updatedItems.findIndex(i => i.id === item.id);
        if (itemIndex !== -1) {
          updatedItems[itemIndex] = {
            ...updatedItems[itemIndex],
            name: translatedName || updatedItems[itemIndex].name,
            text: translatedText,
            translated: true
          };
        }
      } catch (error) {
        console.error(`翻译项目 ID: ${item.id} 失败:`, error);
        MessagePlugin.error(`翻译失败: ${error.message || '未知错误'}`);
      }
    }

    // 更新文本列表
    textItems.value = updatedItems;

    MessagePlugin.success(`翻译完成，已翻译 ${items.length} 个文本`);
  } catch (error) {
    console.error('翻译过程出错:', error);
    MessagePlugin.error('翻译过程出错: ' + (error.message || '未知错误'));
  } finally {
    isTranslating.value = false;
  }
};

// 导入到父组件（直接从翻译步骤导入）
const importToParent = () => {
  if (textItems.value.length === 0) {
    MessagePlugin.warning('没有可导入的文本');
    return;
  }

  // 显示确认页面
  step.value = 'confirm';
};

// 最终导入到父组件（从确认步骤导入）
const finalImport = () => {
  if (textItems.value.length === 0) {
    MessagePlugin.warning('没有可导入的文本');
    return;
  }

  // 准备导入项目
  const itemsToImport = textItems.value.map(item => ({
    id: uuidv4(),
    type: 'text',
    name: item.name,
    text: item.text,
    originalName: item.originalName,
    originalText: item.originalText,
    synthesizing: false,
    audioUrl: item.audioUrl || null,
    duration: item.duration || null,
    historyId: item.historyId || null,
    language: item.language || 'zh',
    captionPath: item.captionPath || null,
    captionStatus: item.captionStatus || 'none',
    captionGenerating: false,
    captionFormat: item.captionFormat || 'srt',
    translated: item.translated,
    createdAt: new Date().toISOString(),
  }));

  // 发送到父组件
  emit('import-items', itemsToImport);
  MessagePlugin.success(`已将 ${itemsToImport.length} 篇文章导入到TTS处理`);

  // 关闭对话框
  emit('update:visible', false);
};

// 取消操作
const cancel = () => {
  if ((step.value === 'import' && importState.textContent.trim()) ||
    (step.value === 'import' && importState.excelData) ||
    (step.value === 'translate' && textItems.value.length > 0) ||
    (step.value === 'confirm' && textItems.value.length > 0)) {

    confirmMessage.value = '确定要取消操作吗？您的内容将不会被保存。';
    confirmCallback.value = () => {
      emit('update:visible', false);
      emit('cancel');
    };
    confirmDialogVisible.value = true;
  } else {
    emit('update:visible', false);
    emit('cancel');
  }
};
</script>

<style scoped>
.tts-import-translation-dialog {
  :deep(.t-dialog__body) {
    max-height: 80vh;
    overflow-y: auto;
  }
}

.text-detail-dialog {
  :deep(.t-dialog__body) {
    max-height: 70vh;
    overflow-y: auto;
  }
}

.tts-import-translation {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.steps-container {
  margin-bottom: 20px;
}

.process-steps {
  width: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--td-component-border);
}

.section-title {
  font-size: 18px;
  font-weight: 500;
}

.import-options {
  margin-bottom: 20px;
}

.text-import {
  margin-top: 16px;
}

.model-info-wrapper {
  margin-bottom: 16px;
}

.excel-import {
  margin-top: 16px;
}

.file-upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  border: 2px dashed var(--td-component-border);
  border-radius: 8px;
  background-color: var(--td-bg-color-container-hover);
}

.excel-file-selector {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.tip {
  color: var(--td-text-color-secondary);
  font-size: 14px;
  margin: 0;
}

.excel-preview {
  margin-top: 20px;
}

.column-selection {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
}

.selection-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.selection-label {
  min-width: 70px;
  font-weight: 500;
}

.preview-table {
  margin-top: 16px;
  border: 1px solid var(--td-component-border);
  border-radius: 6px;
  overflow: hidden;
}

.batch-actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px 16px;
  background-color: var(--td-bg-color-container-hover);
  border-radius: 6px;
}

.batch-info {
  margin-left: 16px;
  font-weight: 500;
  color: var(--td-brand-color);
}

.batch-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-left: auto;
}

.text-list-container {
  border: 1px solid var(--td-component-border);
  border-radius: 6px;
  padding: 16px;
  background-color: var(--td-bg-color-container);
  margin-bottom: 20px;
}

.text-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--td-component-border);
}

.list-title {
  font-size: 16px;
  font-weight: 500;
}

.list-actions {
  display: flex;
  align-items: center;
}

.text-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.text-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 6px;
  background-color: var(--td-bg-color-container-hover);
  border: 1px solid var(--td-component-border);
  transition: all 0.2s ease;
}

.text-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.text-item.selected {
  background-color: var(--td-brand-color-light);
}

.text-item.translated {
  border-left: 3px solid var(--td-success-color);
}

.item-select {
  margin-right: 12px;
}

.text-content {
  flex: 1;
}

.text-title {
  font-weight: 500;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.translated-tag {
  margin-left: 8px;
}

.text-preview {
  font-size: 14px;
  color: var(--td-text-color-secondary);
  line-height: 1.5;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.translation-area {
  padding: 16px;
  border-radius: 6px;
  background-color: var(--td-bg-color-container-hover);
  margin-bottom: 20px;
}

.translation-header {
  margin-bottom: 16px;
}

.translation-title {
  font-size: 16px;
  font-weight: 500;
}

.translation-options {
  display: flex;
  margin-bottom: 16px;
}

.setting-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.setting-label {
  min-width: 80px;
  font-weight: 500;
}

.setting-select {
  width: 200px;
}

.translation-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.translation-progress {
  margin-top: 16px;
}

.confirm-content {
  margin-bottom: 20px;
}

.confirm-alert {
  margin-bottom: 20px;
}

.confirm-summary {
  border: 1px solid var(--td-component-border);
  border-radius: 6px;
  overflow: hidden;
}

.section-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid var(--td-component-border);
}

/* 详情对话框样式 */
.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-section {
  border: 1px solid var(--td-component-border);
  border-radius: 6px;
  padding: 16px;
  background-color: var(--td-bg-color-container-hover);
}

.detail-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--td-text-color-primary);
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--td-component-border);
}

.detail-value {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.original-text, .translated-text {
  padding: 12px;
  border-radius: 4px;
  border: 1px solid var(--td-component-border);
}

.original-text {
  background-color: var(--td-bg-color-container);
}

.translated-text {
  background-color: var(--td-success-color-1);
}

.translated-text.has-original {
  background-color: var(--td-success-color-1);
}

.text-label {
  font-size: 12px;
  font-weight: 500;
  color: var(--td-text-color-secondary);
  margin-bottom: 6px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.text-content {
  font-size: 14px;
  line-height: 1.6;
  color: var(--td-text-color-primary);
  word-wrap: break-word;
  white-space: pre-wrap;
}

.text-content.scrollable {
  max-height: 150px;
  overflow-y: auto;
  padding-right: 8px;
}

.text-content.scrollable::-webkit-scrollbar {
  width: 6px;
}

.text-content.scrollable::-webkit-scrollbar-track {
  background: var(--td-bg-color-container);
  border-radius: 3px;
}

.text-content.scrollable::-webkit-scrollbar-thumb {
  background: var(--td-component-border);
  border-radius: 3px;
}

.text-content.scrollable::-webkit-scrollbar-thumb:hover {
  background: var(--td-text-color-placeholder);
}

.status-info {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.create-time {
  font-size: 13px;
  color: var(--td-text-color-secondary);
}

.detail-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid var(--td-component-border);
}
</style>


